<template>
  <section>
    <div v-if="showSearchForm">
    <SearchForm :searchColumns="searchColumn" :pSearchParam="searchParam" :pSearch="search"
                :resetFun="handleRest"></SearchForm>
    </div>
    <el-col :span="24" class="toolbar" >
      <el-form :inline="true">
        <el-form-item>
          <el-button v-perm="'Mycustomer/add'" plain icon="el-icon-circle-plus-outline" type="primary" @click="handleAdd">新增客户</el-button>
        </el-form-item>
        <el-form-item>
          <el-button v-perm="'Mycustomer/recovery'" plain icon="el-icon-folder-remove"   type="danger" @click="recovery" :disabled="this.sels.length===0">
            回收公海
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData" v-perm="'Mycustomer/exportData'"  icon="el-icon-upload" plain>导出</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-tooltip  content="显示/隐藏搜索框" placement="bottom-end" effect="light" >
            <el-button type="warning" plain size="medium"  @click="showSearchForm = !showSearchForm" icon="el-icon-search" circle></el-button>
          </el-tooltip>
        </el-form-item>
      </el-form>
    </el-col>
    <!--列表-->
    <!-- 动态渲染表格列 -->
    <el-table :data="customerLists"    v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;"  :max-height="tableMaxHeight" row-key="id">
      <el-table-column type="selection" width="45">
      </el-table-column>
      <el-table-column prop="customerName" label="客户名" width="170" :header-align="'center'" :align="'left'" fixed="left">
        <template scope="scope">
          <el-button v-perm="'Mycustomer/update'" type="text" size="small" @click="handleEdit(scope.$index, scope.row)">
            <i class="el-icon-edit-outline"/> 编辑
          </el-button>
          <el-button v-perm="'Mycustomer/addorder'" type="text" size="small"
                     @click="placeOrder(scope.$index, scope.row)"> <i class="el-icon-sold-out"/>下单
          </el-button>
          <el-button v-perm="'Mycustomer/show'" type="text" size="small" @click="showDetails(scope.$index, scope.row)">
            <i class="el-icon-tickets"/>  查看
          </el-button>
          {{scope.row.customerName}}
        </template>
      </el-table-column >
      <el-table-column prop="companyName" label="公司" width="100" sortable :header-align="'center'" :align="'left'">
      </el-table-column>
      <el-table-column prop="totalDealCount" label="累计成交次数" width="160" sortable :header-align="'center'"
                       :align="'center'">
      </el-table-column>
      <el-table-column prop="totalAmount" label="累计金额" width="110" sortable :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="orderProductCount" label="累计下单数量" width="150" sortable :header-align="'center'"
                       :align="'center'">
      </el-table-column>
      <el-table-column prop="label.customerLabel" label="客户级别" width="120" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="source.customerSource" label="客户来源" width="100" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="type.customerType" label="客户销售渠道" width="120" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="notes" label="备注" width="200" :header-align="'center'" :align="'left'">
      </el-table-column>
      <el-table-column prop="follow.date" label="最近活跃时间" width="180" :header-align="'center'" :align="'center'">
        <template slot-scope="scope">
          <el-button v-if="scope.row.follow && scope.row.follow.date" type="text" size="small"
                     @click="allFollowUp(scope.$index, scope.row.follow)">{{ scope.row.follow.date }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="salesMan.adminName" label="归属人" width="120" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column prop="phoneNumber" label="联系方式" width="150" :header-align="'center'" :align="'center'">
        <template #default="{ row, $index }">
          <span v-if="currentPhoneIndex !== $index">{{ formatPhoneNumber(row.phoneNumber) }}</span>
          <span v-else>{{ row.phoneNumber }}</span>
          <el-button
              v-if="shouldShowButton(row.phoneNumber)"
              size="mini"
              circle
              icon="el-icon-view"
              @click="handlePhoneNumberClick($index)"
              class="phoneButton"
          >
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址" width="150" :header-align="'center'" :align="'center'">
      </el-table-column>
      <el-table-column label="置顶" width="100" :header-align="'center'" :align="'center'">
        <template slot-scope="scope">
          <custom-switch
              :value="scope.row.personalTop === 1"
              checkedInfo="开"
              uncheckedInfo="关"
              @change="(personalTop) => handleTopChange(scope.row,personalTop)"
          ></custom-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" :align="'center'" width="180" fixed="right">
        <template scope="scope">
          <el-button v-perm="'Mycustomer/update'" type="text" size="small" @click="handleEdit(scope.$index, scope.row)">
            <i class="el-icon-edit-outline"/> 编辑
          </el-button>
          <el-button v-perm="'Mycustomer/addorder'" type="text" size="small"
                     @click="placeOrder(scope.$index, scope.row)"> <i class="el-icon-sold-out"/>下单
          </el-button>
          <el-button v-perm="'Mycustomer/show'" type="text" size="small" @click="showDetails(scope.$index, scope.row)">
            <i class="el-icon-tickets"/>  查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="[5,10, 30, 50,100]"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage" :page-size="pageSize"
                     :total="totals" style="float:right; margin-right: 40px;"  >
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <el-dialog title="客户编辑" :visible.sync="editFormVisible" :close-on-click-modal="false" width="58%">
      <el-form :model="editForm" label-width="130px" :rules="editFormRules" ref="editForm">
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item prop="companyName">
              <template #label>
                公司名称 <i class="el-icon-office-building icon-size"></i>
              </template>
              <el-input v-model="editForm.companyName" auto-complete="off" readonly ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  prop="customerName">
              <template #label>
                客户名称  <i class="el-icon-user icon-size"></i>
              </template>
              <el-input v-model="editForm.customerName" auto-complete="off" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item  prop="phoneNumber">
              <template #label>手机号  <i class="el-icon-mobile-phone icon-size"></i> </template>
              <el-input maxlength="11" show-word-limit v-model="editForm.phoneNumber" auto-complete="off" readonly ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item :label="index === 0 ? '客户电话' : ''" v-for="(telPhone, index) in editForm.telPhone" :key="index" style="width: 395px">
              <el-input v-model="editForm.telPhone[index]" readonly auto-complete="off" placeholder="请输入客户电话" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item prop="area" >
          <template #label>
            所属地区  <i class="el-icon-map-location icon-size"/>
          </template>
          <el-cascader
              style="width: 275px"
              :options="pcaTextArr"
              v-model="editForm.area"
          :disabled="true">
          </el-cascader>
        </el-form-item>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item prop="address">
              <template #label>
                详细地址  <i class="el-icon-location-information icon-size"></i>
              </template>
              <el-input v-model="editForm.address" auto-complete="off" style="width: 500px" readonly></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item  prop="sourceId">
              <template #label>客户来源 <i class="el-icon-position icon-size"></i></template>
              <el-select v-model="editForm.sourceId" placeholder="请选择客户来源" style="width: 275px">
                <el-option v-for="item in custoSource"
                           :label="item.customerSource"
                           :value="item.id"
                :disabled="true">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item  prop="labelId">
              <template #label>客户级别 <i class="el-icon-star-off icon-size"></i></template>
              <el-select v-model="editForm.labelId" placeholder="请选择客户级别" style="width: 275px">
                <el-option v-for="item in custoLabel"
                           :label="item.customerLabel"
                           :value="item.id"
                           :disabled="true">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item  prop="typeId">
              <template #label>客户销售渠道 <i class="el-icon-shopping-cart-full icon-size"></i></template>
              <el-select v-model="editForm.typeId" placeholder="请选择客户销售渠道" style="width: 275px">
                <el-option v-for="item in custoType"
                           :label="item.customerType"
                           :value="item.id"
                           :disabled="true">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item label="备注信息">
              <template #label>
                备注信息  <i class="el-icon-document icon-size"/>
              </template>
              <el-input type="textarea" v-model="editForm.notes" auto-complete="off" style="width: 500px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="28">
          <el-col :span="12">
            <el-form-item  prop="pricture">
              <template #label>客户图片  <i class="el-icon-picture-outline icon-size"></i> </template>
              <el-image class="edit_show_image" :src="editForm.picture" fit="contain"  ></el-image>
            </el-form-item>
          </el-col>
          <el-form-item label="修改图片">
            <template #label>修改图片  <i class="el-icon-edit-outline icon-size"></i></template>
            <el-upload
                class="upload-demo"
                name="file"
                :action="this.$uploadURL"
                :on-remove="handleFileRemove"
                :on-success="handleFileUploadedit"
                :on-exceed="handleFileExceed"
                :file-list="fileList"
                :limit="1"
                accept=".jpg,.png,.gif,.qlv"
                list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false;">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>
    <!--    客户回访记录页面-->
    <el-dialog title="活跃记录" :visible.sync="followUpFormVisible" :close-on-click-modal="false">
      <el-table :data="followUpForm" v-loading="followLoading">
        <el-table-column label="回访时间" prop="date" width="200" :header-align="'center'" :align="'center'">
        </el-table-column>
        <el-table-column label="跟进记录" width="300" :header-align="'center'" :align="'center'">
          <template slot-scope="scope">
            <div v-if="scope.row.recordType === 1">
              <el-button type="text" @click="showOrderDetail(scope.row.orderSn)">{{ scope.row.content }}</el-button>
            </div>
            <div v-else>
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="console.adminName" width="200" :header-align="'center'" :align="'center'">
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="followUpFormVisible = false">我已了解</el-button>
      </div>
    </el-dialog>
    <!--    创建订单记录的抽屉样式-->
    <el-drawer title="订单创建记录"
               :visible.sync="orderDrawer"
               direction="rtl"
               size="50%"
               @close="orderDrawer=false"
    >
      <!-- 描述信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;margin-left: 50px">
        <el-col :span="24">
          <span>以下是{{this.copyOrderSn}}订单的产品信息，选购数量信息等部分信息，具体详细信息请到订单页面查看!</span>
        </el-col>
      </el-row>
      <el-divider></el-divider> <!-- 添加一个分割线 -->

      <el-table :data="productList" style="width: 100%" border>
        <el-table-column prop="productName" label="产品名称" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="picture" label="产品图片" width="150" :align="'center'">
          <template slot-scope="scope">
            <img :src="scope.row.picture" :preview-src-list="[scope.row.picture]" alt="Product Image"
                 style="width: 100px; height: 100px;">
          </template>
        </el-table-column>
        <el-table-column prop="price" label="产品价格" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="costPrice" label="售价" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="orderNum" label="选购数量" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="salePrice" label="成交价" width="100" :align="'center'"></el-table-column>
        <el-table-column prop="orderAmount" label="金额" width="100" :align="'center'"></el-table-column>
      </el-table>

    </el-drawer>
    <!--    时间记录页面-->
    <el-dialog title="时间记录" :visible.sync="showTimeFormVisible" :close-on-click-modal="false">
      <el-form :model="showTimeForm" label-width="100px" ref="showForm">
        <el-form-item label="更新时间" prop="updateTime">
          <el-input v-model="showTimeForm.updateTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="录入时间" prop="entryCustomerTime">
          <el-input v-model="showTimeForm.entryCustomerTime" readonly></el-input>
        </el-form-item>
        <el-form-item label="最近下单时间" prop="lastDealTime">
          <el-input v-model="showTimeForm.lastDealTime" readonly></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="showTimeFormVisible = false">我已了解</el-button>
      </div>
    </el-dialog>
    <!--查看详情界面-->

    <el-drawer
        title="查看信息"
        :visible.sync="showFormVisible"
        :close-on-click-modal="false"
        size="50%"  @close="handleDrawerClose">
      <div class="head">
        <el-form :model="showForm" label-width="110px" ref="showForm">
          <el-form-item >
            <template #label>
              客户来意 <i class="el-icon-help"></i>
            </template>
            <el-input v-model="showForm.companyName" auto-complete="off" readonly></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="shuju">
        <el-tabs v-model="activeTab" type="border-card">
          <el-tab-pane  name="customer">
            <span slot="label"><i class="el-icon-notebook-2"></i>客户信息</span>
            <div class="customer-detail">
              <div class="section">
                <h4 style="color: rgb(47, 125, 235);">基本信息</h4>
                <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235);  margin-bottom: 8px;">

                <el-form :model="showForm" label-width="100px" ref="showForm">
                  <el-row :gutter="28">
                    <el-col :span="12">
                      <el-form-item label="公司:">
                        <el-input v-model="showForm.companyName" readonly
                                  size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="客户姓名:">
                        <el-input v-model="showForm.customerName" readonly
                                  size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="28">
                    <el-col :span="12">
                      <el-form-item label="手机号:">
                        <el-input  v-model="formattedPhoneNumber" readonly
                                   size="small"
                                   :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }"
                        >
                          <template #append >
                            <el-button

                                v-if="shouldShowButton(showForm.phoneNumber)"
                                size="mini"
                                circle
                                icon="el-icon-view"
                                @click="handleFormPhoneNumberClick"
                                class="phoneButton"
                            >
                            </el-button>
                          </template>
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="电话号:">
                        <el-input size="small" v-for="(phone, index) in showForm.telPhone" :key="index" v-model="showForm.telPhone[index]" auto-complete="off" readonly style="width: 150px; margin-right: 8px;"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="28">
                    <el-col :span="12">
                      <el-form-item label="客户微信:">
                        <el-input v-model="showForm.customerWx" readonly
                                  size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="客户图片:">
                        <el-image v-for="(url, index) in showForm.picture" :key="index" :src="url" fit="contain" :preview-src-list="showForm.picture" class="show-image"></el-image>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="28">
                    <el-col :span="12">
                      <el-form-item label="所属地区:">
                        <el-input v-model="showForm.area" readonly
                                  size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="详细地址:">
                        <el-input v-model="showForm.address" readonly
                                  size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius:'50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="录入时间:">
                        <el-input :value="showForm.entryCustomerTime" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="修改时间:">
                        <el-input :value="showForm.updateTime" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <h4 style="color: rgb(47, 125, 235);">客户属性</h4>
                  <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235); margin-top: 8px; margin-bottom: 8px;">
                  <el-row :gutter="28">
                    <el-col :span="12">
                      <el-form-item label="客户销售渠道:">
                        <el-input :value="typeName" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%', color: '#333' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="客户级别:">
                        <el-input :value="labelName" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="客户来源:">
                        <el-input :value="sourceName" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>

                      </el-form-item>
                    </el-col>
                  </el-row>
                  <h4 style="color: rgb(47, 125, 235);">订单属性</h4>
                  <hr style="border: none; height: 2px; background-color: rgb(47, 152, 235); margin-top: 8px; margin-bottom: 8px;">
                  <el-row :gutter="24">
                    <el-col :span="12">
                      <el-form-item label="累计成交次数:">
                        <el-input :value="showForm.totalDealCount+' 次'" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>

                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="下单产品数量:">
                        <el-input :value="showForm.orderProductCount+' 箱'" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="累计金额:">
                        <el-input :value="showForm.totalAmount+' 元'" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="最后成交时间:">
                        <el-input :value="showForm.lastDealTime" readonly size="small"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%' }">
                        </el-input>

                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row :gutter="28">
                    <el-col :span="24">
                      <el-form-item label="备注信息:">
                        <el-input :value="showForm.notes" readonly size="small" type="textarea"
                                  :style="{ backgroundColor: '#f0f4f7', borderRadius: '50%', 'white-space': 'pre-wrap' }">
                        </el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane  name="contacts">
            <span slot="label"><i class="el-icon-s-custom"></i>归属人</span>
            <div class="contacts">
              <el-table :data="salesDetails">
                <el-table-column prop="adminName" label="姓名"></el-table-column>
                <el-table-column prop="phone" label="手机号码"></el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane name="Order">
            <span slot="label"><i class="el-icon-tickets"></i>订单信息</span>
            <div class="contacts">
              <el-table :data="acquisitionOrders" highlight-current-row v-loading="listLoading"
                        @selection-change="selsChange" style="width: 100% " :border="true">
                <el-table-column prop="orderSn" label="订单号" width="130" :header-align="'center'" :align="'center'">
                  <template slot-scope="scope">
                    <span style="color: red;">{{ scope.row.orderSn }}</span>
                  </template>
                </el-table-column>
                <el-table-column prop="employee.adminName" label="归属人" width="100" :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="customer.customerName" label="客户名" width="100" :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="orderAmount" label="订单金额" width="105" sortable :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="payType" label="支付方式" width="110" :header-align="'center'" :align="'center'">
                </el-table-column>
                <el-table-column prop="createTime" label="下单时间" width="170" sortable :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="logisticsMethods" label="物流方式" width="80" :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="logisticsCompanies" label="物流公司" width="80" :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="trackingNumber" label="物流单号" width="120" :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column prop="orderState" label="订单状态" width="80" :header-align="'center'" :align="'center'">
                  <template scope="scope">
                    <span v-if="scope.row.orderState == 3" style="color: orange">待发货</span>
                    <span v-if="scope.row.orderState == 4" style="color: #50bfff">已发货</span>
                    <span v-if="scope.row.orderState == 5" style="color: lightgreen">交易成功</span>
                    <span v-if="scope.row.orderState == 6" style="color: lightcoral">订单取消</span>
                  </template>
                </el-table-column>
                <el-table-column prop="lastOperationTime" label="最后操作时间" width="160" sortable :header-align="'center'"
                                 :align="'center'">
                </el-table-column>
                <el-table-column label="操作" width="220" :header-align="'center'" :align="'center'">
                  <template scope="scope">
                    <el-button type="text" size="small" @click="deleteOrder(scope.$index, scope.row)">删除订单</el-button>
                  </template>
                </el-table-column>

              </el-table>

            </div>
          </el-tab-pane>
          <el-tab-pane  name="track">
            <span slot="label"><i class="el-icon-document-add"></i>跟进记录</span>
            <div class="track">
              <el-form :inline="true">
                <el-form-item label="客户跟进">
                  <el-input type="textarea" :rows="2" placeholder="请输入与客户的详细跟进信息" v-model="showForm.content"></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="follow">添加跟进记录</el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane  name="reminder">
            <span slot="label"><i class="el-icon-alarm-clock"></i>提醒时间</span>
            <div class="reminder">
              <el-form label-width="80px">
                <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                  <el-form :inline="true">
                    <el-form-item>
                      <el-button type="primary" @click="Notyetdone">创建任务提醒</el-button>
                    </el-form-item>
                  </el-form>
                </el-col>
                <!-- ... 其他提醒时间信息 ... -->
              </el-form>
            </div>
          </el-tab-pane>
          <el-tab-pane label="销售机会" name="sale">
            <span slot="label"><i class="el-icon-sold-out"></i>销售机会</span>
            <div class="sale">
              <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
                <el-form :inline="true">
                  <el-form-item>
                    <el-button type="primary" @click="Notyetdone">创建销售机会</el-button>
                  </el-form-item>
                </el-form>
              </el-col>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-drawer>
  </section>
</template>
<script>
import {mapMutations, mapState} from 'vuex';
import {commonColumn} from './constants'
import {isArray} from '../../utils';
import {pcaTextArr} from "element-china-area-data";
//import NProgress from 'nprogress'
// import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';
import CustomSwitch from '@/components/CustomSwitch.vue';
export default {
  components: {
    CustomSwitch
  },
  data() {
    return {
      currentPhoneIndex: null,
      tableMaxHeightOffset: 100,
      isPhoneNumberVisible: false, // 表单中手机号是否可见
      clickCount: 0, // 当天已点击次数
      maxClicksPerDay: 100, // 每天最大点击次数
      lastReset: null, // 上次重置点击次数的时间
      topStatus: {},  // 用于存储每行数据的置顶状态，只在需要时进行更新
      topList: [],
      showSearchForm: false,
      pcaTextArr,
      productList:[],//记录创建订单的详细信息
      orderDrawer:false,
      copyOrderSn:'',
      acquisitionOrders: [],//所有订单
      ordercustomerId: '',
      //1.分页查询的相关数据
      pageSizes: [10, 30, 50,100,200], // 可选择的每页条数
      gotoPage: '', // 输入框的跳转页数
      customerLists: [],
      total: 0,
      totals: 0,
      currentPage: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],//列表选中列
      fileList: [],
      loginId: '',//登录人id
      //2.高级查询相关数据
      keyword: '',
      showFormVisible: false,//详情界面是否显示
      activeTab: 'customer',
      showLoading: false,
      editFormVisible: false,//编辑界面是否显示
      editLoading: false,
      editFormRules: {
        customerType: [
          {required: true, message: '请输入客户销售渠道', trigger: 'blur'}
        ],
        customerLabel: [
          {required: true, message: '请输入客户级别', trigger: 'blur'}
        ],
        customerSource: [
          {required: true, message: '请输入客户来源', trigger: 'blur'}
        ]
      },
      //显示所有时间
      showTimeFormVisible: false,
      showTimeForm: {
        entryCustomerTime: '',
        lastDealTime: '',
        updateTime: '',
      },
      //编辑界面数据
      editForm: {
        CustomerId: null,
        companyName: '',
        customerName: '',
        phoneNumber: '',
        address: '',
        labelId: '',
        typeId: '',
        sourceId: '',
        picture: [],
        updateTime: '',
        notes: '',
        telPhone: [''],
      },
      //客户回访记录页面
      followUpFormVisible: false,
      followUpForm: {
        date: '',
        content: '',
      },
      followLoading: false,
      //查看界面数据
      showForm: {
        id: '',
        companyName: '',
        customerName: '',
        phoneNumber: '',
        address: '',
        labelId: '',
        typeId: '',
        sourceId: '',
        totalDealCount: '',
        orderProductCount: '',
        lastDealTime: '',
        salesmanId: '',
        picture: [],
        content: '',
        telPhone: '',
        entryCustomerTime: '',
        updateTime:'',
      },
      salesDetails: [],//存储业务员详细信息；

      showFormRules: {
        customerType: [
          {required: true, message: '请输入客户销售渠道', trigger: 'blur'}
        ],
        customerLabel: [
          {required: true, message: '请输入客户级别', trigger: 'blur'}
        ],
        customerSource: [
          {required: true, message: '请输入客户来源', trigger: 'blur'}
        ]
      },
      //业务员           // //员工所属部门
      salesMan: [],        // departments: [],
      // 客户销售渠道
      custoLabel: [],
      // 客户销售渠道
      custoType: [],
      //客户来源
      custoSource: [],
      columnTitle: [
        {label: '客户id', checked: false, prop: 'id'},
        {label: '公司名', checked: false, prop: 'companyName'},
        {label: '客户名', checked: false, prop: 'customName'},
        {label: '手机号', checked: false, prop: 'phoneNumber'},
        {label: '累计金额', checked: false, prop: 'totalAmount'},
        {label: '累计成交次数', checked: false, prop: 'totalDealCount'},
        {label: '累计下单产品数量', checked: false, prop: 'orderProductCount'},
        {label: '客户来源', checked: false, prop: 'sources'},
        {label: '客户销售渠道', checked: false, prop: 'types'},
        {label: '客户级别', checked: false, prop: 'labels'},
        {label: '所属业务员', checked: false, prop: 'salesmans'},
        {label: '所属地区', checked: false, prop: 'area'},
        {label: '客户微信', checked: false, prop: 'customerWx'},

        {label: '备注', checked: false, prop: 'notes'},
        {label: '图片', checked: false, prop: 'picture'},
        {label: '录入时间', checked: false, prop: 'entryCustomerTime'},
      ],
      allChangeValue: false,
      searchColumn: commonColumn,

      searchParam: {
        customerLabelId: [],
        customerSourceId: [],
        customerTypeId: [],
        customerName: '',
        phone: '',
        time: ''
      },
    }
  },
  computed: {
    // 计算当前表单中的手机号
    formattedPhoneNumber() {
      return this.isPhoneNumberVisible
          ? this.showForm.phoneNumber
          : this.formatPhoneNumber(this.showForm.phoneNumber);
    },
    //计算表格高度
    tableMaxHeight() {
      // 计算表格最大高度，可以根据需要调整逻辑
      return window.innerHeight - this.tableMaxHeightOffset + 'px';
    },
    typeName() {
      const category = this.custoType.find(item => item.id === this.showForm.typeId);
      return category ? category.customerType : '';
    },
    sourceName(){
      const category = this.custoSource.find(item => item.id === this.showForm.sourceId);
      return category ? category.customerSource : '';
    },
    labelName(){
      const category = this.custoSource.find(item => item.id === this.showForm.sourceId);
      return category ? category.customerSource : '';
    },
  },
  watch: {
    // 监听标签页切换
    activeTab(tab) {
      if (tab === 'contacts') {
        // 获取当前业务员ID
        const id = this.showForm.salesmanId;
        this.fetchSalesDetails(id);
      }
    }
  },
  methods: {
    async handleTopChange(row, personalTop) {
      const originalIsTop = row.personalTop;
      row.personalTop = personalTop ? 1 : 0;

      // 向后端发起请求
      try {
        const response = await this.updateTopStatus(row.id, row.personalTop);
        if (response.success) {
          // 更新数据排序
          if (personalTop) {
            this.customerLists = this.customerLists.filter(item => item.id !== row.id);
            this.customerLists.unshift(row);
          } else {
            this.customerLists = this.customerLists.filter(item => item.id !== row.id);
            const topItems = this.customerLists.filter(item => item.personalTop === 1);
            const nonTopItems = this.customerLists.filter(item => item.personalTop === 0);
            this.customerLists = [...topItems, row, ...nonTopItems];
          }
          this.$message({
            message: personalTop ? '置顶成功' : '取消置顶成功',
            type: 'success'
          });
        } else {
          throw new Error('更新失败');
        }
      } catch (error) {
        this.$message({
          message: error.message || '更新失败',
          type: 'error'
        });
        // 如果请求失败，恢复原始状态
        row.personalTop = originalIsTop;
      }
    },
    updateTopStatus(id, personalTop) {
      const url = personalTop === 1 ? '/customMycustom/personalTop' : '/customMycustom/personalDown';
      const param = { id: id };

      return this.$http.post(url, param)
          .then(response => response.data)
          .catch(error => {
            console.error('请求错误:', error);
            throw new Error('请求失败');
          });
    },
    updateTableMaxHeight() {
      this.$forceUpdate(); // 强制 Vue 重新计算 `computed` 属性
    },
    //手机号隐藏
    //小于2位不隐藏,6位隐藏中间的两位,大于6位隐藏中间的4位
    formatPhoneNumber(phoneNumber) {
      const length = phoneNumber.length;
      if (length <= 2) {
        return phoneNumber;
      } else if (length > 2 && length < 6) {
        return phoneNumber.slice(0, 2) + '**' + phoneNumber.slice(4);
      } else if (length >= 6) {
        return phoneNumber.slice(0, 3) + '****' + phoneNumber.slice(length - 2, length);
      }
      return phoneNumber;
    },
    // 切换电话号码的显示状态
    togglePhoneNumber(index) {
      if (this.currentPhoneIndex === index) {
        this.currentPhoneIndex = null;
      } else {
        this.currentPhoneIndex = index;
      }
    },
    // 判断是否应该显示按钮
    shouldShowButton(phoneNumber) {
      return phoneNumber.length > 2;
    },
    // 处理电话号码按钮点击事件
    handlePhoneNumberClick(index) {
      this.resetClicksIfNeeded();
      if (this.clickCount < this.maxClicksPerDay) {
        this.togglePhoneNumber(index);
        this.clickCount++;
        this.saveClickData();
      } else {
        // 如果超过当天最大点击次数，显示提示信息
        this.$notify({
          title: '提示',
          message: '当前已没有查看次数，请明天再来',
          type: 'warning',
        });
      }
    },
    // 切换表单电话号码的显示状态
    toggleFormPhoneNumber() {
      this.isPhoneNumberVisible = !this.isPhoneNumberVisible;
    },
    // 处理表单中电话号码按钮点击事件
    handleFormPhoneNumberClick() {
      this.resetClicksIfNeeded();
      if (this.clickCount < this.maxClicksPerDay) {
        this.toggleFormPhoneNumber();
        this.clickCount++;
        this.saveClickData();
      } else {
        // 如果超过当天最大点击次数，显示提示信息
        this.$notify({
          title: '提示',
          message: '当前已没有查看次数，请明天再来',
          type: 'warning',
        });
      }
    },
    // 从localStorage加载点击次数数据
    loadClickData() {
      const storedClickCount = localStorage.getItem('clickCount');
      const storedLastReset = localStorage.getItem('lastReset');

      this.clickCount = storedClickCount ? parseInt(storedClickCount, 10) : 0;
      this.lastReset = storedLastReset ? new Date(storedLastReset) : new Date();
    },
    // 将点击次数数据保存到localStorage
    saveClickData() {
      localStorage.setItem('clickCount', this.clickCount);
      localStorage.setItem('lastReset', this.lastReset.toISOString());
    },
    // 检查是否需要重置点击次数
    resetClicksIfNeeded() {
      const now = new Date();
      const lastResetTime = new Date(this.lastReset);

      // 将 lastResetTime 调整到当天的 0:00:00
      lastResetTime.setHours(0, 0, 0, 0);

      // 如果当前时间已经过了 lastResetTime 的 24 小时
      if (now.getTime() - lastResetTime.getTime() >= 24 * 60 * 60 * 1000) {
        this.clickCount = 0;
        this.lastReset = now;
        this.saveClickData();
      }
    },

    // 处理关闭抽屉事件
    handleDrawerClose() {
      this.isPhoneNumberVisible = false;
    },
    allChange(flag) {
      if (flag) {
        this.columnTitle.forEach((item) => {
          item.checked = true;
        })
        this.exportOrder();
      } else {
        this.columnTitle.forEach((item) => {
          item.checked = false;
        })
      }
    },
    exportOrder() {
      //选中横列数据
      let id = this.sels.map(item => item.id);
      id = id.join(',');
      this.$http.post("/customMycustom/export", {
        exportDto: this.columnTitle,
        id: id
      }, {responseType: 'blob'}).then((res) => {
        if (!res) {
          return;
        }
        const blob = new Blob([res.data], {
          type: "application/vnd.openxmlformats-officeedocument.sheet;charset=utf-8",
        }); //处理二进制文件，指定字符集
        const link = document.createElement("a");
        link.href = window.URL.createObjectURL(blob); //将下载连接赋值到a标签href属性上
        link.download = "orderInfo.xls"; //所要下载的文件名，与后端响应的名字相对应
        link.click(); //执行下载

      });
    },
    //获取订单产品
    showOrderDetail(orderSn){
      this.orderDrawer=true;
      this.copyOrderSn=orderSn;
      this.$http.post("/orderProducid/" + orderSn).then(res => {
        this.productList = res.data;
      });
    },

    ...mapMutations(['updateEnumMap']),
    getColumnEnum() {
      this.searchColumn.forEach(async col => {
        if (!col.enum) return;
        if (typeof col.enum !== 'function') return this.$store.commit('updateEnumMap', {key: col.prop, value: data});
        const {data} = await col.enum();
        this.$store.commit('updateEnumMap', {key: col.prop, value: data})
      })
    },
    addInput(index) {
      this.editForm.telPhone.splice(index + 1, 0, '');
    },
    removePhone(index) {
      this.editForm.telPhone.splice(index, 1); // 移除指定索引的电话号码
    },
    //获取订单列表
    getAcquisitionOrders() {
      let para = {
        currentPage: 1,
        pageSize: 500,
        ordercustomerId: this.ordercustomerId,
      };
      this.listLoading = true;
      this.$http.post("/orderList/getCustomerOrder", para).then(res => {
        this.totals = res.data.total;
        this.acquisitionOrders = res.data.records.map(order => ({
          ...order,
          receipt: order.receipt ? order.receipt.split(',') : [],
          voucher: order.voucher ? order.voucher.split(',') : []
        }));
        this.currentPage = para.currentPage; // 更新当前页数
        this.listLoading = false;
      }).catch(result => {
        this.$message.error("系统繁忙，请稍后重试!!!")
      })
    },
    //获取联系人信息
    async fetchSalesDetails(id) {
      try {
        //清空数组，准备存放新的数组
        this.salesDetails = [];
        // 根据业务员ID异步请求详细信息
        const response = await this.$http.get(`/employee/${id}`);

        this.salesDetails.push(response.data); // 根据实际响应结构调整

      } catch (error) {
        console.error("获取业务员详细信息失败:", error);
      }
    },
    handlePageSizeChange(val) {
      this.pageSize = val;
      this.getcustomerLists();
    },
//数据导出
    exportData() {
      const logininfo = JSON.parse(localStorage.getItem("logininfo"));
      const LoginId = parseInt(logininfo.id, 10);
      // 发起 GET 请求
      location.href = "https://www.kongqichong.com:8080/customMycustom/mycustomerexport/" + LoginId
    },
    gettypeNameById(typeId) {
      const category = this.custoType.find(item => item.id === typeId);
      return category ? category.customerType : '';
    },
    getlabelNameById(labelId) {
      const category = this.custoLabel.find(item => item.id === labelId);
      return category ? category.customerLabel : '';
    },
    getsourceNameById(sourceId) {
      const category = this.custoSource.find(item => item.id === sourceId);
      return category ? category.customerSource : '';
    },
    //获取类型
    getType() {
      this.$http.get("/customerType").then(res => {
        this.custoType = res.data;
      })
    },
    //获取业务员
    getSalesman() {
      this.$http.get("/customSalesman").then(res => {
        this.salesMan = res.data;
      })
    },
    //获取标签
    getLabel() {
      this.$http.get("/customerLabel").then(res => {
        this.custoLabel = res.data;
      })
    },

    //获取来源
    getSerouce() {
      this.$http.get("/customerSource").then(res => {
        this.custoSource = res.data;
      })
    },
    //1.分页获取用户列表
    getcustomerLists() {
      const logininfo = JSON.parse(localStorage.getItem("logininfo"));
      this.loginId = logininfo.id;
      const params = {};
      for (let key in this.searchParam) {
        if (this.searchParam[key]) {
          if (isArray(this.searchParam[key])) {
            if (this.searchParam[key].length > 0) {
              params[key] = this.searchParam[key].join(',');
            } else {
              params[key] = '';
            }
          } else {
            params[key] = this.searchParam[key];
          }
        } else {
          params[key] = '';
        }
      }
      const param = {...{currentPage: this.currentPage, pageSize: this.pageSize, loginId: this.loginId}, ...params}
      this.listLoading = true;
      this.$http.post("/customMycustom/getMyCustom", param).then((res) => {
        this.customerLists = res.data.records.map(order => ({
          ...order,
          picture: order.picture ? order.picture.split(',') : [],
          telPhone: order.telPhone ? order.telPhone.split(',') : [],
        }));

        this.totals = res.data.total;
        this.listLoading = false;
      }).catch(res => {
        this.$message.warning("系统繁忙，请稍后重试!!!")
      });
    },

    placeOrder: function (index, row) {
      this.$confirm(`确定要为客户 "${row.customerName}" 下单吗？`, '确认下单', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击了确定按钮，执行下单操作
        //跳转到创建订单
        const customerId = row.id;
        const customerName = row.customerName;
        const customerType = row.type.customerType;
        const customerLabel = row.label.customerLabel;
        const customerSource = row.source.customerSource;
        this.$router.push({
          name: '客户订单',
          params: {
            orderData: {
              customerId: customerId,
              customerName: customerName,
              customerType: customerType,
              customerSource: customerSource,
              customerLabel: customerLabel,
            }
          }
        });
      }).catch(() => {
        // 用户点击了取消按钮，不执行下单操作
      });
    },
    //2.点击分页实现
    // 每页显示条数改变时调用
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1; // 重置当前页码为1
      this.getcustomerLists();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getcustomerLists();
    },

    //4.修改用户状态
    handleDisable: function (row) {
      this.$confirm('确认禁用该用户吗?禁用后该账户不可再进行操作！', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.put("/customSalesmancustom/" + row.id).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.getcustomerLists();
          } else {
            this.$message.warning("系统繁忙，请稍后重试!!!");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.warning("系统繁忙，请稍后重试!!!");
        })
      }).catch(() => {
      });
    },

    //5.删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/customMycustom/" + row.id).then(res => {
          if (res.data.success) {
            //计算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            // 当删除最后一页的最后一条数据，并且当前不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getcustomerLists();
          } else {
            this.$message.warning("系统繁忙，请稍后重试!!!");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.warning("系统繁忙，请稍后重试!!!");
        })
      }).catch(() => {
      });
    },
    deleteOrder: function (index, row) {
      this.$confirm('确认删除该订单信息记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/orderList/" + row.orderSn).then(res => {
          if (res.data.success) {
            this.$message({
              message: '删除成功,请关闭当前页面刷新数据！',
              type: 'success'
            });
            this.getcustomerLists();
          } else {
            this.$message.warning("系统繁忙，请稍后重试!!!");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.warning("系统繁忙，请稍后重试!!!");
        })
      }).catch(() => {
      });
    },

    //6.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;

    },

    //7.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/customMycustom", ids).then(res => {
          if (res.data.success) {
            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            //当删除最后一页的所有数据，并且不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - this.sels.length) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getcustomerLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });

    },
//8.显示查看界面
    showDetails: function (index, row) {
      this.ordercustomerId = row.id;
      this.showForm = Object.assign({}, row);
      this.showForm.updateTime=this.$formatTimeNew(this.showForm.updateTime);
      this.showForm.entryCustomerTime = this.$formatTimeNew(this.showForm.entryCustomerTime)
      this.showForm.lastDealTime = this.$formatTimeNew(this.showForm.lastDealTime)
      this.showFormVisible = true;
      this.getType();
      this.getLabel();
      this.getSerouce();
      this.getAcquisitionOrders();
    },
    //8.显示编辑界面
    handleEdit: function (index, row) {
      this.editForm = Object.assign({}, row);
      console.log('数据:查询', this.editForm)
      this.editFormVisible = true;
      this.getType();
      this.getLabel();
      this.getSerouce()
    },
    //显示所有的时间记录
    showTime: function (index, row) {
      this.showTimeForm = Object.assign({}, row);
      this.showTimeFormVisible = true;
      //时间格式化
      this.showTimeForm.updateTime = this.$formatTimeNew(this.showTimeForm.updateTime);
      this.showTimeForm.entryCustomerTime = this.$formatTimeNew(this.showTimeForm.entryCustomerTime);
      this.showTimeForm.lastDealTime = this.$formatTimeNew(this.showTimeForm.lastDealTime);

    },
    //放回公海
    recovery: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认将选中的客户回收到公海客户中吗？，该操作不可逆！', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.put("/customMycustom/recovery", ids).then(res => {
          if (res.data.success) {
            //处理当前页
            //算总页数
            let totalPage = Math.ceil(this.total / this.pageSize);
            //当删除最后一页的所有数据，并且不是第一页，就让当前页-1
            if (this.currentPage == totalPage && (this.total - this.sels.length) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.$message({
              message: '回收成功！',
              type: 'success'
            });
            this.getcustomerLists();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!!【500】");
          }
          this.listLoading = false;
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!!【400,404】");
        })
      }).catch(() => {
      });

    },
    Notyetdone: function () {
      this.$message('该功能暂未完成');
    },
//客户回访
    follow: function () {
      this.$refs.showForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
                const logininfo = JSON.parse(localStorage.getItem("logininfo"));
                const LoginInfoId = logininfo.id;
                let para = {
                  customId: this.showForm.id,//客户id
                  content: this.showForm.content,
                  loginInfoId: LoginInfoId,
                };
                this.$http.put("/customReturnVisit/follow", para).then(res => {
                  if (res.data.success) {
                    this.$message({
                      message: '客户回访信息提交成功',
                      type: 'success'
                    });
                  } else {
                    this.$message.error("系统繁忙，请稍后重试!!!");
                  }
                  this.getcustomerLists();
                });
              }
          );
        }
      });
    },
    /**
     * 客户所有回访记录
     */

    /**
     * 客户所有回访记录
     */
    allFollowUp: function (index, row) {
      this.followUpFormVisible = true;
      const customId = row.customId;
      this.followLoading = true;
      this.$http.get("/customReturnVisit/" + customId).then(res => {
        this.followUpForm = res.data;
        this.followLoading = false;
      })
    },
    //9.显示新增界面
    handleAdd: function () {
      // 先检查是否有新增权限
      if (this.hasAddPermission()) {
        this.$confirm('确定要添加客户吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 用户点击确定时执行的逻辑
          this.$router.push({name: '添加我的客户',}); // 执行页面跳转
        }).catch(() => {
          // 用户点击取消时执行的逻辑仍在当前页面；
        });
      } else {
        this.$message.warning('当前账户无权限进入新增客户操作页面，请联系管理员赋予权限');
      }
    },
    //判断权限
    hasAddPermission() {
      const menus = JSON.parse(localStorage.getItem("menus"));

      // 递归检查是否存在id为97的菜单
      function checkMenu(menu) {
        if (menu.id === 97) {
          return true; // 找到了指定的菜单
        }
        // 递归检查子菜单
        if (menu.children && menu.children.length > 0) {
          for (const childMenu of menu.children) {
            if (checkMenu(childMenu)) {
              return true; // 子菜单中找到了指定的菜单
            }
          }
        }
        return false; // 没有找到指定的菜单
      }

      // 遍历根菜单
      return menus && menus.some(menu => checkMenu(menu));
    },

    //10.提交编辑数据
    editSubmit: function () {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true;
            this.editForm.updateTime = new Date();
            const logininfo = JSON.parse(localStorage.getItem("logininfo"));
            this.editForm.loginId = logininfo.id;
            let para = Object.assign({}, this.editForm);
            para.telPhone = para.telPhone.filter(phone => phone !== '');
            para.telPhone = para.telPhone.join(','); // 将 telPhone 数组转换为字符串
            para.picture = para.picture.join(','); // 将标签数组转换为字符串
            this.$http.put("/customMycustom", para).then(res => {
              if (res.data.success) {
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                this.$refs['editForm'].resetFields();
              } else {
                this.$message.error("系统繁忙，请稍后重试!!!【500】");
              }
              this.editLoading = false;
              this.editFormVisible = false;
              this.getcustomerLists();
            });
          });
        }
      });
    },
//文件删除时的回调
    handleFileRemove(file, fileList) {
      //正式删除
      var fileName = null;
      if (file.response) {  //上传图片的时候点了删除
        fileName = file.response.resultObj;
      } else {  //点击修改回显的图片，点了删除
        fileName = file.url;
      }
      //为了方便参数传递,需要转换路径写法,把/替换为_
      fileName = fileName.replaceAll("/", "_");
      //发送请求
      this.$http.delete("/minio/" + fileName).then(res => {
        if (res.data.success) {
          this.$message.success("删除成功");
          this.fileList = [];
          this.addForm.picture = "";
        } else {
          this.$message.error("删除失败");
        }
      })
    },

    //文件上传成功之后的回调
    handleFileUpload(response) {
      if (response.success) {
        this.addForm.picture = response.resultObj;
      }
    },
    //文件上传成功之后的修改页面回调
    handleFileUploadedit(response) {
      if (response.success) {
        this.editForm.picture.push(response.resultObj);
      }
    },
    //上传超过数量的回调
    handleFileExceed() {
      this.$message.error("不能上传多张图片");
    },
    handleRest() {
      this.currentPage = 1;
      this.pageSize = 10;
    },
    search() {
      this.getcustomerLists();
    }
  },
  mounted() {
    this.getType();
    this.getLabel();
    this.getSerouce();
    this.getcustomerLists();
    this.getColumnEnum();
    // 在组件挂载时，加载点击次数数据并检查是否需要重置
    this.loadClickData();
    this.resetClicksIfNeeded();
    // 窗口大小变化和页面缩放时重新计算高度
    window.addEventListener('resize', this.updateTableMaxHeight);
    window.addEventListener('zoom', this.updateTableMaxHeight);
  },
  beforeDestroy() {
    // 移除事件监听器
    window.removeEventListener('resize', this.updateTableMaxHeight);
    window.removeEventListener('zoom', this.updateTableMaxHeight);
  },
  created() {
    this.customerLists.forEach((item) => {
      this.$set(this.topStatus, item.id, false);
    });
  },
}

</script>

<style scoped lang="scss">
.search-form {
  .field-box {
    display: flex;

    .check-all {
      margin-right: 30px;
    }
  }

  .el-form-item {
    margin-bottom: 0;
  }

}.dropdown-menu-with-scroll {
   max-height: 200px; /* 设置最大高度 */
   overflow-y: auto; /* 超出高度时滚动 */
 }
.customer-detail {
  margin-top:0px;
}
.section {
  margin-bottom: 5px;
  padding: 30px;
  background: #f9f9f9;
  border-radius: 4px;
}
.contacts {
  margin-bottom: 5px;
  padding: 30px;
  background: #f9f9f9;
  border-radius: 4px;
}
.phoneButton {
  margin-left: 10px;
  padding: 5px;
}
</style>